### Replication Package for "Why is Intermediating Houses so Difficult? Evidence from iBuyers"
### Buchak, Matvos, Piskorski, and Seru
###
###
### buchak@stanford.edu

### Creates mobility analysis tables for model validation appendix.

library(data.table)
library(lfe)
library(ggplot2)
library(stargazer)


source('0_helper_functions.r')


Figure_A14 <- function() 

{
  
  data.in <- fread('../data/raw/zillow/Metro_mean_doz_pending_uc_sfrcondo_month.csv')  
  
  
  # Melt from wide to long format
  dt_long <- melt(
    data.in,
    id.vars = c("RegionID", "SizeRank", "RegionName", "RegionType", "StateName"),
    variable.name = "Date",
    value.name = "Data"
  )
  
  dt_long[, Date := as.IDate(Date, format = "%Y-%m-%d")]
  
  by.date <- dt_long[,j=list(pct_under_30 = mean(Data < 30,na.rm=T)),by=c('Date')]  
  
  ggplot(by.date[Date <= as.Date('2022/04/01',format='%Y/%m/%d')]) + geom_line(aes(x=Date,y=pct_under_30)) + geom_point(aes(x=Date,y=pct_under_30)) + 
    theme_classic() + xlab(NULL) + ylab(NULL) + scale_y_continuous(labels = function(x) {paste0(round(100*x,0),'%')}) + coord_cartesian(ylim = c(0,1))
  
  ggsave('../out/figures/A14.png',height=4,width=6,units='in',dpi = 300)
  
}

Figure_A14()

